package ovm.management.administration.users;

import ovm.entity.UsersEntity;
import ovm.management.AbstractManager;
import ovm.management.security.MD5Hasher;

import javax.persistence.Query;

public class UsersManager extends AbstractManager {

    public static int SAME_LOGIN_ERROR = 1;

    public static int findUserEntry (String login) {
        Query query = em.createQuery("SELECT u FROM UsersEntity u WHERE u.login = :login");
        query.setParameter("login", login);
        if (query.getResultList().size() > 0) return SUCCESSFUL;
        return UNSUCCESSFUL;
    }
    
    public static UsersEntity getUserByLogin (String login) {
        Query query = em.createQuery("SELECT u FROM UsersEntity u WHERE u.login = :login");
        query.setParameter("login", login);
        return (UsersEntity) query.getResultList().get(0);
    }
    
    public static int deleteUser (UsersEntity user) {
        try {
            em.getTransaction().begin();
            em.remove(user);
            em.getTransaction().commit();
        } catch (Exception e) {
            em.getTransaction().rollback();
            e.printStackTrace();
            return UNSUCCESSFUL;
        }

        return SUCCESSFUL;
    }
    
    public static int changeUser (UsersEntity user, String newPassword, int newRule) {
        try {
            em.getTransaction().begin();
            user.setPassword(MD5Hasher.getMD5Hash(newPassword));
            user.setRule(newRule);
            em.merge(user);
            em.getTransaction().commit();
        } catch (Exception e) {
            em.getTransaction().rollback();
            e.printStackTrace();
            return UNSUCCESSFUL;
        }
        
        return SUCCESSFUL;
    }
    
    public static int addUser (String login, String password, int rule) {
        if (findUserEntry(login) == SUCCESSFUL) {
            return SAME_LOGIN_ERROR;
        }

        try {
            em.getTransaction().begin();

            UsersEntity newUser = new UsersEntity();
            newUser.setLogin(login);
            newUser.setPassword(MD5Hasher.getMD5Hash(password));
            newUser.setRule(rule);
    
            em.persist(newUser);
            em.getTransaction().commit();
        } catch (Exception e) {
            em.getTransaction().rollback();
            e.printStackTrace();
            return UNSUCCESSFUL;
        }

        return SUCCESSFUL;
    }

}
